﻿using FlyingEye.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp;

namespace FlyingEye
{
    internal class DbMigratorHostedService : IHostedService
    {
        private readonly IHostApplicationLifetime _hostApplicationLifetime;

        public DbMigratorHostedService(IHostApplicationLifetime hostApplicationLifetime, IConfiguration configuration)
        {
            

            _hostApplicationLifetime = hostApplicationLifetime;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var application = AbpApplicationFactory.Create<FlyingEyeDbMigratorModule>(options =>
            {
                options.UseAutofac();
                options.Services.AddLogging(c => c.AddSerilog());
            }))
            {
                application.Initialize();

                var configuration = application.ServiceProvider.GetRequiredService<IConfiguration>();
                var mainAsselbly = Assembly.GetAssembly(typeof(Program));

                if (mainAsselbly is null)
                {
                    throw new System.Exception("主函数程序集为 NULL！");
                }

                configuration["StartPath"] = Path.GetDirectoryName(mainAsselbly.Location);

                await application
                    .ServiceProvider
                    .GetRequiredService<FlyingEyeDbMigrationService>()
                    .MigrateAsync();

                application.Shutdown();

                _hostApplicationLifetime.StopApplication();
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
